package com.the_ring.chapter08.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;



public class PieAnimation extends View {

    private Paint mPaint = new Paint();         // 创建一个画笔对象
    private int mDrawingAngle = 0;              // 当前绘制的角度
    private Handler mHandler = new Handler();   // 声明一个处理器对象
    private boolean isRunning = false;          // 是否正在播放动画

    public PieAnimation(Context context) {
        this(context, null);
    }

    public PieAnimation(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint.setColor(Color.GREEN);
    }

    // 开始播放动画
    public void start() {
        mDrawingAngle = 0;
        isRunning = true;
        mHandler.post(mRefresh);
    }

    // 定义一个绘图刷新任务
    private Runnable mRefresh = new Runnable() {
        @Override
        public void run() {
            mDrawingAngle += 3;
            if (mDrawingAngle <= 270) {
                invalidate();
                mHandler.postDelayed(this, 70);
            } else {
                isRunning = false;
            }
        }
    };


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isRunning) {
            int width = getMeasuredWidth();
            int height = getMeasuredHeight();
            int diameter = Math.min(width, height);
            RectF rectF = new RectF((width - diameter) / 2, (height - diameter) / 2, (width + diameter) / 2, (height + diameter) / 2);
            canvas.drawArc(rectF, 0, mDrawingAngle, true, mPaint);
        }
    }
}
